﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TianYuan.Core.Dependency;
using TianYuan.Data.Dapper;

namespace TianYuan.Data.Dapper
{
    public class UnitOfWorkInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            var method = invocation.MethodInvocationTarget;
            
            if (method.IsDefined(typeof(TransactionalAttribute), false))
            {
                IDbContext dbContext = IocManager.Instance.Resolve<IDbContext>();
                try
                {
                    dbContext.BeginTransaction();
                    invocation.Proceed();
                    dbContext.Commit();
                    
                }
                catch (Exception)
                {
                    dbContext.Rollback();
                    throw;
                }
            }
            else
            {
                invocation.Proceed();
            }
            
        }
        
    }
}
